<?php

namespace backend\modules\wechat\controllers;

use backend\controllers\AdminController;
use backend\modules\wechat\models\WechatReplyRuleSearch;
use common\components\Helper;
use common\models\wechat\WechatAccounts;
use common\models\wechat\WechatReplyKeyword;
use common\models\wechat\WechatReplyRule;
use Yii;
use common\models\wechat\WechatNewsReply;
use backend\modules\wechat\models\WechatNewsReplySearch;
use yii\db\Exception;
use yii\db\Query;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\components\Upload;

/**
 * NewsReplyController implements the CRUD actions for WechatNewsReply model.
 */
class NewsReplyController extends AdminController
{
    public $replies = null;

    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }


    /**
     * Lists all WechatNewsReply models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new WechatReplyRuleSearch();
        $searchModel->processor = 'news';
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }



    /**
     * Displays a single WechatNewsReply model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new WechatNewsReply model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new WechatNewsReply();

        if (Yii::$app->request->isPost) {
            return $this->ruleKwdSave();
//            return $this->redirect(['view', 'id' => $model->id]);
        } else {

            $rid = Yii::$app->request->get('id');
            $reply = [];
            if(!empty($rid)){
                $reply = (new Query())->select('*')->from(['news'=>WechatReplyRule::tableName()])
                    ->where('id=:rid',[':rid'=>$rid])
                    ->one();

                $reply['keywords'] = (new Query())->select('*')->from(['kwd'=>WechatReplyKeyword::tableName()])
                    ->where('rid=:rid',[':rid'=>$rid])
                    ->all();
                foreach($reply['keywords'] as &$kw) {
                    $kw = Helper::array_elements(['type', 'content'], $kw);
                }
            }

            $replies = (new Query())->select('*')->from(['news'=>WechatNewsReply::tableName()])
                ->where('parent_id=-1 and rid=:rid',[':rid'=>$rid])
                ->orderBy('displayorder desc,id asc')
                ->all();
            if(!empty($replies)) {
                $parent_id = $replies[0]['id'];
                Yii::$app->db->createCommand()->update(WechatNewsReply::tableName(),['parent_id'=>$parent_id],'rid=:rid',[':rid'=>$rid])->execute();
                Yii::$app->db->createCommand()->update(WechatNewsReply::tableName(),['parent_id'=>0],'rid=:rid and id=:pid',[':rid'=>$rid,':pid'=>$parent_id])->execute();
            }

            $rows = (new Query())->select('*')->from(['news'=>WechatNewsReply::tableName()])
                ->where('rid=:rid',[':rid'=>$rid])
                ->orderBy('parent_id asc,id asc')
                ->all();

            foreach($rows as &$row) {
                if(!empty($row['thumb'])) {
                    $row['thumb'] = Upload::checkGetUrl($row['thumb']);
                }
                if (empty($row['parent_id'])) {
                    $replies[$row['id']][] = $row;
                } else {
                    $replies[$row['parent_id']][] = $row;
                }
            }
            $replies = array_values($replies);



            return $this->render('create', [
                'model' => $model,
                'replies' => $replies,
                'reply' => $reply,
                'rid' => $rid,
            ]);
        }
    }



    /**
     * Deletes an existing WechatNewsReply model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }



    public function actionCheck()
    {
        $result = (new Query())->select('*')->from(WechatReplyKeyword::tableName())->where('wid=:wid and content=:content',[':wid'=>WechatAccounts::WID,':content'=>Yii::$app->request->post('keyword')])->all();
        if (!empty($result)) {
            $keywords = array();
            foreach ($result as $reply) {
                $keywords[] = $reply['rid'];
            }
            $rules = (new Query())->select('*')->from(WechatReplyRule::tableName())->where(['in','id',$keywords])->all();

            exit(@json_encode($rules));
        }
        exit('success');
    }

    /**
     * Finds the WechatNewsReply model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return WechatNewsReply the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = WechatNewsReply::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     * @return string
     * 验证规则
     */
    protected function validate()
    {
        $this->replies = @json_decode(htmlspecialchars_decode(Yii::$app->request->post('replies')), true);
        if(empty($this->replies)) {
            return '必须填写有效的回复内容.';
        }
        $column = array('id', 'parent_id', 'title', 'author', 'displayorder', 'thumb', 'description', 'content', 'url', 'incontent', 'createtime');
        foreach($this->replies as $i => &$group) {
            foreach($group as $k => &$v) {
                if(empty($v)) {
                    unset($group[$k]);
                    continue;
                }
                if (trim($v['title']) == '') {
                    return '必须填写有效的标题.';
                }
                if (trim($v['thumb']) == '') {
                    return '必须填写有效的封面链接地址.';
                }
                $v['thumb'] = str_replace(Yii::getAlias('@uploadurl'), '', $v['thumb']);
                $v['content'] = htmlspecialchars_decode($v['content']);
                $v['createtime'] = time();
                $v = Helper::array_elements($column, $v);
            }
            if(empty($group)) {
                unset($i);
            }
        }
        if(empty($this->replies)) {
            return '必须填写有效的回复内容.';
        }
        return '';
    }


    /**
     * @return string
     * 保存
     */
    protected function ruleKwdSave()
    {
        $rule = array(
            'wid' => WechatAccounts::WID,
            'name' => Yii::$app->request->post('name'),
            'module' => 'system',
            'status' => Yii::$app->request->post('status'),
            'displayorder' => intval(Yii::$app->request->post('displayorder')),
            'processor' => 'news',
        );
        if(!empty(Yii::$app->request->post('istop'))) {
            $rule['displayorder'] = 255;
        } else {
            $rule['displayorder'] = Helper::range_limit($rule['displayorder'], 0, 254);
        }


        //验证
        $msg = $this->validate();
        if(is_string($msg) && trim($msg) != '') {
            return $this->dialog($msg);
        }

        //开启事务
        $tr = Yii::$app->db->beginTransaction();


        $rid = intval(Yii::$app->request->post('rid'));
        try{
            if (!empty($rid)) {
                $result = Yii::$app->db->createCommand()->update(WechatReplyRule::tableName(),$rule,'id=:id',[':id'=>$rid])->execute();
            } else {
                $result = Yii::$app->db->createCommand()->insert(WechatReplyRule::tableName(),$rule)->execute();
                $rid = Yii::$app->db->getLastInsertID();
            }

            //插入关键字
            if (!empty($rid)) {

                Yii::$app->db->createCommand()->delete(WechatReplyKeyword::tableName(),'rid=:rid and wid=:wid',[':rid'=>$rid,':wid'=>WechatAccounts::WID])->execute();
                $keywords = Yii::$app->request->post('keywords');
                $keywords = @json_decode(htmlspecialchars_decode($keywords), true);
                $rowtpl = array(
                    'rid' => $rid,
                    'wid' => WechatAccounts::WID,
                    'module' => 'system',
                    'status' => $rule['status'],
                    'displayorder' => $rule['displayorder'],
                    'created_at' => time(),
                    'updated_at' => time(),
                    'content' => $keywords?$keywords:'',
                    'type' => 1
                );
                foreach($keywords as $kw) {
                    $krow = $rowtpl;
                    $krow['type'] = Helper::range_limit($kw['type'], 1, 4);
                    $krow['content'] = $kw['content'];
                    Yii::$app->db->createCommand()->insert(WechatReplyKeyword::tableName(),$krow)->execute();
                }

                if($this->selfSave($rid)){
                    $tr->commit();      //提交事务
                    return $this->dialog('保存成功','success','index');
                }
            }
            return $this->dialog('回复规则保存失败, 请联系网站管理员！','success','index');
        }catch (Exception $e){
            $tr->rollBack();        //回滚
            return $this->dialog('更新失败:错误信息为:'.addslashes($e->getMessage()));
        }
    }


    /**
     * @param $rid
     * @return bool
     * 保存图文
     */
    protected function selfSave($rid)
    {
        $replies = (new Query())->select('id')->from(WechatNewsReply::tableName())->where('rid=:rid',[':rid'=>$rid])->indexBy('id')->all();
        $replyids = array_keys($replies);
        $indexs = [];
        foreach($this->replies as &$group) {
            $parent_id = -1;
            foreach ($group as $reply) {
                if ($parent_id <= 0) {
                    if ($reply['parent_id'] == 0) {
                        $parent_id = $reply['id'];
                    } elseif ($reply['parent_id'] > 0) {
                        $parent_id = $reply['parent_id'];
                    }
                }
            }
            if ($parent_id == -1) {
                $i = 0;
                foreach ($group as $reply) {
                    if (!$i) {
                        $i++;
                        $reply['rid'] = $rid;
                        $reply['parent_id'] = 0;
                        Yii::$app->db->createCommand()->insert(WechatNewsReply::tableName(),$reply)->execute();
                        $parent_id = Yii::$app->db->getLastInsertID();
                    } else {
                        $reply['parent_id'] = $parent_id;
                        $reply['rid'] = $rid;
                        Yii::$app->db->createCommand()->insert(WechatNewsReply::tableName(),$reply)->execute();
                    }
                }
                Yii::$app->db->createCommand()->update(WechatNewsReply::tableName(),['parent_id' => 0],'id=:id',[':id'=>$parent_id])->execute();
            } else {
                $i = 0;
                foreach ($group as $reply) {

                    if (!$i) {
                        $new_parent_id = $reply['id'];
                        $i++;
                    }
                    $arr[] = $reply['id'];
                    $reply['parent_id'] = $parent_id;
                    if (in_array($reply['id'], $replyids)) {
                        Yii::$app->db->createCommand()->update(WechatNewsReply::tableName(),$reply,'id=:id',[':id'=>$reply['id']])->execute();
                        $index = array_search($reply['id'], $replyids);
                        unset($replyids[$index]);
                    } else {
                        $reply['rid'] = $rid;
                        Yii::$app->db->createCommand()->insert(WechatNewsReply::tableName(),$reply)->execute();
                    }
                }
                if (!in_array($parent_id, $arr)) {
                    $parent_id = $new_parent_id;
                }

                Yii::$app->db->createCommand()->update(WechatNewsReply::tableName(),['parent_id' => $new_parent_id],'parent_id=:parent_id',[':parent_id'=>$parent_id])->execute();
                Yii::$app->db->createCommand()->update(WechatNewsReply::tableName(),['parent_id' => 0],'id=:id',[':id'=>$new_parent_id])->execute();
            }
        }

        if (!empty($replyids)) {
            Yii::$app->db->createCommand()->delete(WechatNewsReply::tableName(),['in','id',$replies])->execute();
        }
        return true;
    }


}
